<template>
  <el-dialog
    v-model="visible"
    :title="readonly ? '商家黑名单' : '商家黑名单管理'"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 搜索表单 -->
    <el-form v-if="!readonly" :model="queryParams" ref="queryRef" :inline="true" class="mb-4">
      <el-form-item label="卖家ID" prop="seller_id">
        <el-input
          v-model="queryParams.seller_id"
          placeholder="请输入卖家ID"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卖家昵称" prop="seller_nick">
        <el-input
          v-model="queryParams.seller_nick"
          placeholder="请输入卖家昵称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row v-if="!readonly" :gutter="10" class="mb-4">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="blacklistList"
      @selection-change="handleSelectionChange"
      border
      max-height="400"
    >
      <el-table-column v-if="!readonly" type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="卖家ID" prop="seller_id" align="center" min-width="120" />
      <el-table-column label="卖家昵称" prop="seller_nick" align="center" min-width="120">
        <template #default="{ row }">
          <el-tag>{{ row.seller_nick || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拉黑原因" prop="reason" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column label="状态" prop="status" align="center" width="100">
        <template #default="{ row }">
          <el-switch
            v-if="!readonly"
            v-model="row.status"
            :active-value="'0'"
            :inactive-value="'1'"
            active-text="启用"
            inactive-text="禁用"
            @change="handleStatusChange(row)"
          />
          <el-tag v-else :type="row.status === '0' ? 'success' : 'info'">
            {{ row.status === '0' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建者" prop="create_by_name" align="center" width="120">
        <template #default="{ row }">
          <el-tag type="info" size="small">{{ row.create_by_name || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" align="center" width="160">
        <template #default="{ row }">
          {{ formatDate(row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column v-if="!readonly" label="操作" align="center" width="150" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑表单对话框 -->
    <el-dialog
      v-model="formVisible"
      :title="formTitle"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="卖家ID" prop="seller_id">
          <el-input v-model="form.seller_id" placeholder="请输入卖家ID" />
        </el-form-item>
        <el-form-item label="卖家昵称" prop="seller_nick">
          <el-input v-model="form.seller_nick" placeholder="请输入卖家昵称" />
        </el-form-item>
        <el-form-item label="拉黑原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入拉黑原因"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="'0'"
            :inactive-value="'1'"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSellerBlacklistList,
  addSellerBlacklist,
  updateSellerBlacklist,
  deleteSellerBlacklist,
  batchDeleteSellerBlacklist
} from '@/api/blacklist'

// ==================== Props & Emits ====================
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

// ==================== Reactive Data ====================
const visible = ref(false)
const loading = ref(false)
const multiple = ref(true)
const blacklistList = ref([])
const selectedIds = ref([])

// 查询参数
const queryParams = reactive({
  seller_id: '',
  seller_nick: ''
})

// 表单
const formVisible = ref(false)
const formTitle = ref('新增商家黑名单')
const form = reactive({
  id: null,
  seller_id: '',
  seller_nick: '',
  reason: '',
  remark: '',
  status: '0'  // ✅ 默认启用
})

// 表单校验规则
const rules = {
  seller_id: [
    { required: false, message: '卖家ID和卖家昵称至少填写一个', trigger: 'blur' }
  ],
  seller_nick: [
    { required: false, message: '卖家ID和卖家昵称至少填写一个', trigger: 'blur' }
  ]
  // reason 改为选填，不需要校验规则
}

// Refs
const queryRef = ref(null)
const formRef = ref(null)

// ==================== Watch ====================
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadBlacklistData()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// ==================== Methods ====================

/**
 * 加载黑名单数据
 */
async function loadBlacklistData() {
  loading.value = true
  try {
    const response = await getSellerBlacklistList(queryParams)
    if (response.code === 200) {
      blacklistList.value = response.data || []
    } else {
      ElMessage.error(response.msg || '加载失败')
    }
  } catch (error) {
    console.error('加载商家黑名单失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索
 */
function handleQuery() {
  loadBlacklistData()
}

/**
 * 重置搜索
 */
function resetQuery() {
  queryRef.value?.resetFields()
  loadBlacklistData()
}

/**
 * 新增
 */
function handleAdd() {
  resetForm()
  formTitle.value = '新增商家黑名单'
  formVisible.value = true
}

/**
 * 编辑
 */
function handleEdit(row) {
  resetForm()
  Object.assign(form, row)
  formTitle.value = '编辑商家黑名单'
  formVisible.value = true
}

/**
 * 状态切换
 */
async function handleStatusChange(row) {
  try {
    const response = await updateSellerBlacklist(row.id, {
      status: row.status
    })
    if (response.code === 200) {
      ElMessage.success(row.status === '0' ? '已启用' : '已禁用')
    } else {
      // 恢复原状态
      row.status = row.status === '0' ? '1' : '0'
      ElMessage.error(response.msg || '状态更新失败')
    }
  } catch (error) {
    // 恢复原状态
    row.status = row.status === '0' ? '1' : '0'
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

/**
 * 删除
 */
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(
      `确认删除卖家"${row.seller_nick || row.seller_id}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteSellerBlacklist(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadBlacklistData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 批量删除
 */
async function handleBatchDelete() {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedIds.value.length} 条数据吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await batchDeleteSellerBlacklist(selectedIds.value)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadBlacklistData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 表格选择变化
 */
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

/**
 * 提交表单
 */
async function submitForm() {
  try {
    await formRef.value?.validate()

    // 校验至少填写一个
    if (!form.seller_id && !form.seller_nick) {
      ElMessage.warning('卖家ID和卖家昵称至少填写一个')
      return
    }

    const isEdit = !!form.id
    const apiFunc = isEdit ? updateSellerBlacklist : addSellerBlacklist
    const apiParams = isEdit ? [form.id, form] : [form]

    const response = await apiFunc(...apiParams)
    if (response.code === 200) {
      ElMessage.success(isEdit ? '修改成功' : '新增成功')
      formVisible.value = false
      loadBlacklistData()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== false) {
      console.error('提交失败:', error)
    }
  }
}

/**
 * 重置表单
 */
function resetForm() {
  form.id = null
  form.seller_id = ''
  form.seller_nick = ''
  form.reason = ''
  form.remark = ''
  form.status = '0'  // ✅ 重置为默认启用状态
  formRef.value?.clearValidate()
}

/**
 * 格式化日期
 */
function formatDate(dateString) {
  if (!dateString) return '-'
  return dateString.replace('T', ' ').substring(0, 19)
}

/**
 * 关闭对话框
 */
function handleClose() {
  emit('update:modelValue', false)
}

/**
 * 暴露方法给父组件
 */
defineExpose({
  refresh: loadBlacklistData
})
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>

